package com.jushu.storbox.callback;

import java.util.ArrayList;

public class ITCallbackObserver<ReqType, ResType> implements ITCallback<ReqType, ResType> {

	private final ArrayList<ITCallback<ReqType, ResType>> observerList = new ArrayList<ITCallback<ReqType, ResType>>();

	@Override
	public void onStart(ReqType procData) {
		synchronized(observerList) {
			for(ITCallback<ReqType, ResType> call : observerList) {
				call.onStart(procData);
			}
		}
	}

	@Override
	public void onProgress(ReqType procData, int progress, long proccedSize, long sizeByThis) {
		synchronized(observerList) {
			for(ITCallback<ReqType, ResType> call : observerList) {
				call.onProgress(procData, progress, proccedSize, sizeByThis);
			}
		}
	}

	@Override
	public void onSuccess(ReqType procData, ResType response) {
		synchronized(observerList) {
			for(ITCallback<ReqType, ResType> call : observerList) {
				call.onSuccess(procData, response);
			}
		}
	}

	@Override
	public void onFailure(ReqType procData, Throwable t) {
		synchronized(observerList) {
			for(ITCallback<ReqType, ResType> call : observerList) {
				call.onFailure(procData, t);
			}
		}
	}
	
	public void registerCallback(ITCallback<ReqType, ResType> callback) {
		synchronized(observerList) {
			if(!observerList.contains(callback)) {
				observerList.add(callback);
			}
		}
	}
	
	public void unRegisterCallback(ITCallback<ReqType, ResType> callback) {
		synchronized(observerList) {
			int index = observerList.indexOf(callback);
			if(index != -1) {
				observerList.remove(index);
			}
		}
	}

}
